package com.tao.springcloud.controller;

import com.tao.springcloud.entities.CommonResult;
import com.tao.springcloud.entities.Payment;
import com.tao.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @ClassName OrderController
 * @Author HETAO
 * @Date 2020/5/9 11:16
 */
@RestController
@Slf4j
@RequestMapping("consumer")
public class OrderController {
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVER";

    //发现服务
    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @GetMapping("{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id) /**/{
        return restTemplate.getForObject(PAYMENT_URL+"/payment?id="+id,CommonResult.class);
    }

    @GetMapping("consumer")
    public CommonResult<Payment> createPayment(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL+"/payment/",payment,CommonResult.class);
    }

    @GetMapping("discovery")
    public Object getEureka() {
        //获取所有注册的服务
        List<String> services = discoveryClient.getServices();
        services.forEach(item -> log.debug(item));
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVER");
        instances.forEach(item -> {
            log.debug(item.getInstanceId() +"<===>"+ item.getHost()  + "<===>"+ item.getPort());
        });
        return null;
    }
    @GetMapping("test")
    public String test(@RequestParam("id") Long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVER");
        if (CollectionUtils.isEmpty(instances)) {
            return null;
        }
        ServiceInstance instance = loadBalancer.instance(instances);
        URI uri = instance.getUri();
        String result = restTemplate.getForObject(uri + "/payment?id=" + id, String.class);
        return result;
    }

    @GetMapping("/consumer/get")
    public String getPaymentById(@RequestParam("id") Long id) {
        String result = restTemplate.getForObject(PAYMENT_URL + "/payment/get?id=" + id, String.class);
        return result;
    }
}
